package com.fifth.apartment.controller;


import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.fifth.apartment.entity.Bills;
import com.fifth.apartment.result.Result;
import com.fifth.apartment.service.IBillsService;
import com.fifth.apartment.vo.FormTradeNumVO;
import com.fifth.apartment.vo.room.RoomAptVo;
import com.qiniu.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-07-24
 */
@RestController
@RequestMapping("/app/bills")
@Api(tags = "账单接口")
@Slf4j
public class BillsController {

    @Autowired
    private IBillsService service;
    @GetMapping("getBills")
    @ApiOperation("根据用户id查账单")
    public Result getBills(int userId){
        Bills bills = service.getBills(userId);
        if (bills!=null){
            return new Result(true,"查询成功",bills);
        }else {
            return new Result(false,"查询失败");
        }
    }

    @GetMapping("getRoomApt")
    @ApiOperation("根据用户id查房屋")
    public Result getRoomApt(int userId){
        RoomAptVo roomAptVo = service.getRoomApt(userId);
        if (roomAptVo!= null){
            return new Result(true,"查询成功",roomAptVo);
        }else {
            return new Result(false, "查询失败");
        }
    }

    @GetMapping("getWaterValue")
    @ApiOperation("根据用户id查房屋水费")
    public Result getWaterValue(int userId){
        Integer waterValue = service.getWaterValue(userId);
        if (waterValue!= null){
            return new Result(true,"查询成功",waterValue);
        }else {
            return new Result(false,"查询失败");
        }
    }

    private final String TRADE_FINISHED = "TRADE_FINISHED";
    private final String TRADE_SUCCESS = "TRADE_SUCCESS";

    @Value("${alipay.notify_url}")
    private String notifyUrl;

    @Value("${alipay.return_url}")
    private String returnUrl;

    @Value("${alipay.charset}")
    private String charset;

    @Value("${alipay.alipay_public_key}")
    private String alipayPublicKey;

    @Value("${alipay.sign_type}")
    private String signType;

    @Resource
    private AlipayClient alipayClient;


    @GetMapping("doPay")
    @ApiOperation("用支付宝支付水费")
    public Result doPay(Integer userId, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws Exception{
        long outTradeNo = System.currentTimeMillis();
        log.info("支付订单，订单号：" + outTradeNo);

        // 相应请求API的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        // 在公共参数中设置回跳和通知地址
        alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(notifyUrl);

        //获得水费
//        log.info("userId========"+userId);
        Integer waterValue = service.getWaterValue(userId);
        // 封装商品信息
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("total_amount", waterValue);
        bizContent.put("subject", "公寓水费");
        // 沙箱默认值为：QUICK_WAP_WAY
        bizContent.put("product_code", "QUICK_WAP_WAY");
        //bizContent.put("time_expire", "2022-08-01 22:00:00");

        //商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);

        alipayRequest.setBizContent(bizContent.toString());

        //调用SDK生成表单
        String form = "";
        try {
//            form = alipayClient.pageExecute(alipayRequest).getBody();
            form = alipayClient.pageExecute(alipayRequest,"GET").getBody();

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        FormTradeNumVO vo = new FormTradeNumVO();
        vo.setForm(form);
        vo.setTradeNum(outTradeNo);
        service.updateOutTradeNo(userId,outTradeNo);
        httpResponse.setContentType("text/html;charset=" + charset);
        //直接将完整的表单html输出到页面
//        httpResponse.getWriter().write(form);
//        httpResponse.getWriter().flush();
//        httpResponse.getWriter().close();

        return new Result(true,"运行成功",vo);
    }


    /**
     * @param tradeNum 商户网站唯一订单号(out_trade_no) 或 支付宝交易号(trade_no)
     * @throws Exception
     * @deprecated 具体API参数说明参考：https://opendocs.alipay.com/open/02ivbt
     */
    @GetMapping("query")
    @ResponseBody
    public Result query(@RequestParam String tradeNum,@RequestParam Integer userId) throws Exception {
        //创建API对应的request类
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        // 商户网站唯一订单号
        bizContent.put("out_trade_no", tradeNum);
        // 支付宝交易号
        //bizContent.put("trade_no", tradeNum);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = alipayClient.execute(request);

        // 打印结果
        log.debug(response.getBody());

        // 根据response中的结果继续业务逻辑处理
        if (response.isSuccess()) {
            log.info("调用支付宝成功");
            log.info(response.getSubMsg());
            /**
             * 获取状态交易状态：
             * WAIT_BUYER_PAY（交易创建，等待买家付款）
             * TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）
             * TRADE_SUCCESS（交易支付成功）
             * TRADE_FINISHED（交易结束，不可退款）
             */
            String tradeStatus = response.getTradeStatus();
            log.info("交易状态：" + tradeStatus);

            log.info("支付宝交易号：" + response.getTradeNo());
            log.info("商家订单号：" + response.getOutTradeNo());
            log.info("买家支付宝账号：" + response.getBuyerLogonId());
            log.info("买家在支付宝的用户id：" + response.getBuyerUserId());
            log.info("买家在支付宝的用户id：" + response.getBuyerUserId());
            Integer flag = service.updateWaterValue(userId);
            return new Result(true,"成功支付",flag);
        } else {
            log.error("调用支付宝失败");
            log.error(response.getSubCode());
            log.error(response.getSubMsg());
            return new Result(false,"支付失败");
        }

    }


    @GetMapping("/return")
    @ApiOperation("返回支付宝通知")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("同步通知");

        //乱码解决，这段代码在出现乱码时使用
        request.setCharacterEncoding("utf-8");

        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<>(8);
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Map.Entry<String, String[]> stringEntry : requestParams.entrySet()) {
            String[] values = stringEntry.getValue();
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(stringEntry.getKey(), valueStr);
        }

        //商户订单号,之前生成的带用户ID的订单号
        String outTradeNo = new String(params.get("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        //支付宝交易号
        String tradeNo = new String(params.get("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        //付款金额
        String totalAmount = new String(params.get("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

        log.info("trade_no:" + tradeNo);
        log.info("outTradeNo:" + outTradeNo);
        log.info("totalAmount:" + totalAmount);
        Integer userId = service.getUserId(outTradeNo);
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset, signType);

        if (signVerified) {
            System.out.println("验签成功-跳转到成功后页面");
            if(query(outTradeNo,userId).isSuccess()){
                System.out.println("成功支付");
            }else{
                System.out.println("未成功支付");
            }
            //跳转至支付成功后的页面,
            response.sendRedirect("http://localhost:5173/#/myRoom");
            return "redirect:http://localhost:5173/#/myRoom";
        } else {
            System.out.println("验签失败-跳转到充值页面让用户重新充值");
            response.sendRedirect("http://localhost:5173/#/myRoom");
            return "redirect: http://localhost:5173/#/myRoom";
        }
    }
//    @GetMapping("realPay")
//    @ResponseBody
//    public
}

